<template>
  <a-drawer :open="visible" title="入库签收" @close="onClose">
    <template #closeIcon>
      <div class="express-bar"></div>
      <div class="express-btn">
        <CloseCircleOutlined :size="32" @click="onClose" />
      </div>
    </template>
    <a-card size="small" title="基本信息">
      <a-descriptions size="small" :column="3">
        <a-descriptions-item label="单据编号">{{ options.no }}</a-descriptions-item>
        <a-descriptions-item label="经销商">{{ options.related?.dealer?.name }}</a-descriptions-item>
        <a-descriptions-item label="供应商">{{ options.related?.supplier?.name }}</a-descriptions-item>
        <a-descriptions-item label="仓库">{{ options.related?.warehouse?.name }}</a-descriptions-item>
        <a-descriptions-item label="入库状态">
          <span>{{ getDescByValue('STORE_STATUS_ENUM', options.into_status) }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="订单总额">{{ options.order_amount }}</a-descriptions-item>
        <a-descriptions-item label="备注">{{ options.remark }}</a-descriptions-item>
        <a-descriptions-item label="单据日期">{{ options.create_time }}</a-descriptions-item>
        <a-descriptions-item label="签收备注">
            <a-input v-model:value="sign_remark" placeholder="签收备注"></a-input>
        </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card class="smart-margin-top10" size="small" :tab-list="tabList" :active-tab-key="activeKey" @tabChange="(key) => (activeKey = key)">
      <template #customTab="{ tab }">
        <span class="ant-card-head-title" :style="compactModeClass">
          {{ tab }}
        </span>
      </template>
      <template v-if="activeKey === 'inventory'">
        <a-table :dataSource="dataList" :columns="columns" :pagination="false" rowKey="id" size="small" bordered>
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.dataIndex === 'real_num'">
              <div class="smart-table-operate">
                <a-input-number v-model:value="record.real_num" :disabled="options.into_status !== 1" placeholder="签收数量" :min="1" @change="changeDialog(true, record)" />
              </div>
            </template>
            <template v-if="column.dataIndex === 'batch_time'">
              <div class="smart-table-operate">
                <a-button @click="changeDialog(true, record)" type="primary" v-show="options.into_status == 1"
                  ><span>{{ record.batch?.map((item) => item.batch_time).join(', ') || '请选择批次' }}</span></a-button
                >
              </div>
            </template>
            <template v-if="column.dataIndex === 'remark'">
              <a-input v-model:value="record.remark" placeholder="备注" />
            </template>
          </template>
        </a-table>
        <!-- <div style="width: 300px; margin-top: 30px">
          <a-input v-model:value="sign_remark" placeholder="签收备注" />
        </div> -->
      </template>
      <template v-if="activeKey === 'log'">
        <PurchaseTracerTimeline :tableData="options.related?.log" />
      </template>
    </a-card>
    <template #footer>
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
      <a-button style="margin-right: 8px" type="primary" @click="submit" :loading="caigouLoading" :disabled="caigouLoading" v-if="options.into_status == 1">签收</a-button>
    </template>
    <a-modal v-model:open="showDialog" @cancel="changeDialog(false)" title="生产日期录入" width="30%" destroyOnClose>
      <div style="display: flex; flex-direction: column">
        批次日期：<a-date-picker v-model:value="pickTime" @change="changeTime" value-format="YYYY-MM-DD" />
        <p style="display: flex; gap: 16px">
          {{ dialogData.goods?.name || '-' }} 数量：{{ dialogData.quantity }}
          <span style="color: red">待录 {{ dialogData.quantity - totalNum }} {{ dialogData.spec?.unit || '-' }}</span>
        </p>
        <div style="max-height: 360px; overflow-y: auto" v-if="dialogData.batch">
          <div style="display: flex; align-items: center; margin-bottom: 4px; font-weight: bold">
            <span style="display: flex; flex: 1; justify-content: center">批次日期</span>
            <span style="display: flex; flex: 1; justify-content: center; color: #6b7280">批次数量</span>
            <span style="display: flex; flex: 1; justify-content: center; color: #6b7280">总计</span>
            <span style="display: flex; flex: 1; justify-content: center; color: #6b7280">库位</span>
          </div>
          <div v-for="(item, index) in dialogData.batch" :key="index" style="display: flex; gap: 4px; margin-bottom: 4px; align-items: center">
            <span style="display: flex; flex: 1; border-style: solid; border-width: 1px; border-color: #d1d5db; height: 30px; align-items: center">{{ item.batch_time }}</span>
            <a-input-number style="flex: 1" v-model:value="item.quantity" :min="1" :precision="0" placeholder="请输入数量" />
            <span style="display: flex; flex: 1; border-style: solid; border-width: 1px; border-color: #d1d5db; height: 30px; align-items: center">{{ item.sign_amount }}</span>
            <a-select style="flex: 1" v-model:value="item.warehouse_location_id" :options="optionsArea" placeholder="库位" />
            <!-- 添加删除按钮 -->
            <a-button type="text" @click="removeBatch(index)" style="padding: 0; margin-left: 4px; color: red">
              <template #icon>
                <CloseOutlined />
              </template>
            </a-button>
          </div>
          <div style="display: flex; align-items: center; margin-top: 4px; font-weight: bold">
            <span style="flex: 1; color: #6b7280; justify-content: center">总计</span>
            <span style="display: flex; flex: 1; color: #6b7280; justify-content: center">{{ totalNum }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <div style="width: 100%; display: flex; align-items: center; justify-content: flex-end">
          <a-button @click="confirmData">确定</a-button>
        </div>
      </template>
    </a-modal>
  </a-drawer>
</template>

<script setup lang="ts">
import PurchaseTracerTimeline from './purchase-tracer-timeline.vue'
import { message } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { searchApi } from '@/api/search/search-api'
import { returnOrderApi } from '@/api/business/storage/store-api'
import { useEnums } from '@/hooks/plugins/useEnums'
const compactModeClass = inject('compactModeClass')
const { getDescByValue } = useEnums()

defineExpose({
  showDrawer
})
const emit = defineEmits(['reload-list'])

// --------------------- Drawer 显示与隐藏 ---------------------
// 签收备注
const sign_remark = ref('')
// 是否展示
const visible = ref(false)
// 详情
const options = ref({})
// 详情tab
const activeKey = ref('inventory')
const tabList = [
  {
    key: 'inventory',
    tab: '商品明细'
  },
  {
    key: 'log',
    tab: '日志记录'
  }
]

function showDrawer(item) {
  sign_remark.value = ''
  options.value = item
  visible.value = true
  searchArea()
}

const onClose = () => {
  visible.value = false
}

// 库位
const optionsArea = ref([])

const searchArea = async () => {
  const data = {
    // fields: 'id,name',
    filter: {
      warehouse_id: options.value?.related?.warehouse_id
    },
    op: { warehouse_id: '=' }
  }
  const res = await searchApi.warehouseLocationList(data)
  optionsArea.value = res.data.map((item) => {
    return {
      value: item.id,
      label: item.code
    }
  })
}
// --------------------- 入库商品 ---------------------
const dataList = computed(() => options.value?.related?.detail || [])
const columns = reactive([
  {
    title: '商品名称',
    dataIndex: ['goods', 'goods_name']
  },
  {
    title: '规格',
    dataIndex: ['spec', 'spec_name']
  },
  {
    title: '单位',
    dataIndex: ['spec', 'unit_name']
  },
  {
    title: '数量',
    dataIndex: 'quantity'
  },
  {
    title: '签收数量',
    dataIndex: 'real_num'
  },
  {
    title: '生产日期',
    dataIndex: 'batch_time'
  },
  {
    title: '采购金额',
    dataIndex: 'purchase_price'
  },
  {
    title: '总计',
    dataIndex: 'purchase_total_price'
  },
  // {
  //   title: '签收记录',
  //   dataIndex: ''
  // },
  // {
  //   title: '上架记录',
  //   dataIndex: ''
  // },
  {
    title: '备注',
    dataIndex: 'remark'
  }
])
// --------------------- 弹窗 ---------------------
const showDialog = ref(false)
const dialogData = ref<any>({})
const quantity = ref()
const changeDialog = (value: boolean, row?: any) => {
  if (row) {
    quantity.value = row.quantity
    dialogData.value = row
  } else {
    dialogData.value = {}
  }

  if (!value) {
    dialogData.value = {}
    pickTime.value = ''
  }
  showDialog.value = value
}

const changeTime = () => {
  dialogData.value.batch ??= []
  if (!dialogData.value.batch.some((item) => item.time === pickTime.value)) {
    dialogData.value.batch.push({
      goods_id: dialogData.value.goods_id,
      spec_id: dialogData.value.goods_spec_id,
      warehouse_id: options.value?.related?.warehouse_id,
      // remark: dialogData.value.remark,
      batch_time: pickTime.value,
      quantity: 0,
      warehouse_location_id: null
    })
  }
}
const totalNum = computed(() => {
  return dialogData.value.batch ? dialogData.value.batch.reduce((sum, item) => sum + Number(item.quantity), 0) : 0
})
// 监听 dialogData.batch 中的每个 item.quantity 变化
watch(
  () => dialogData.value.batch,
  (newBatch) => {
    if (newBatch) {
      dialogData.value.real_num = newBatch.reduce((total, batchItem) => total + Number(batchItem.quantity), 0)
      newBatch.forEach((item) => {
        // 每次数量或单价变化时重新计算 total
        item.sign_amount = (Number(item.quantity) * Number(dialogData.value.purchase_price)).toFixed(2)
      })
    }
  },
  { deep: true, immediate: true } // 深度监听，立即执行
)
const into_status = ref()
const confirmData = () => {
  if (Number(totalNum.value) <= 0) {
    message.error('录入数量要大于0')
    return
  }
  Number(dialogData.value.quantity) < Number(totalNum.value) ? message.error('录入数量不应大于待录数量') : changeDialog(false)
}
const pickTime = ref('')
const caigouLoading = ref(false)
const submit = async () => {
  // 遍历 dataList.value
  into_status.value = 0 // 初始化 into_status 为 0保持响应
  dataList.value.forEach((item) => {
    // 检查 batch 是否存在
    if (!item.batch || item.batch.length === 0) {
      // 如果 batch 不存在或为空，直接将 into_status 设置为 3
      into_status.value = 3
      return // 退出循环
    }
    // 计算 batch 中所有 quantity 的总和
    const batchTotalQuantity = item.batch.reduce((total, batchItem) => total + Number(batchItem.quantity), 0)
    Number(item.quantity) === batchTotalQuantity ? (into_status.value = 2) : (into_status.value = 3)
    // 比较一层的 quantity 和二层 batch 的总和是否一致
    //   if (Number(item.quantity) !== batchTotalQuantity) {
    //     into_status.value = 3
    //     return // 退出循环
    //   }
  })
  // // 如果循环结束，说明所有项都满足条件，设置 into_status 为 2
  // if (into_status.value !== 3) {
  //   into_status.value = 2
  // }

  // 提取所有有效的 batch 内容
  const batchList = dataList.value.flatMap((item) => {
    return (item.batch || []).map((batchItem) => {
      return {
        ...batchItem,
        remark: item.remark
      }
    })
  })
  // console.log(batchList, 'batchList')
  const params = {
    id: options.value.id,
    into_status: into_status.value,
    batch: JSON.stringify(batchList),
    sign_remark: sign_remark.value
  }
  // console.log(params, 'params')
  caigouLoading.value = true
  try {
    const res = await returnOrderApi.signIn(params)
    message.success(res.msg)
    onClose()
    emit('reload-list')
  } catch (error) {
    message.error(error.msg)
    errorSentry.captureError(error)
  } finally {
    caigouLoading.value = false
  }
}
// --------------------- 生产日期录入 ---------------------
const removeBatch = (index: number) => {
  if (dialogData.value.batch && dialogData.value.batch.length > 0) {
    dialogData.value.batch.splice(index, 1)
  }
}
</script>
